﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using VFDDriver.Properties;

namespace VFDDriver.VFD
{
    public class DisplayDriver : IDriver
    {
        #region Properties

        #region Serial Port

        private SerialPort _port;
        /// <summary>TODO: Add description here.</summary>
        public SerialPort Port
        {
            get { return _port; }
        }

        #endregion

        #region Instance

        private static DisplayDriver _instance;
        public static DisplayDriver Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new DisplayDriver();
                return _instance;
            }
        }

        #endregion

        #endregion

        #region Constructors

        #endregion

        #region Methods

        #region IDriver Members

        public bool Initialize()
        {
            _port = new SerialPort(Settings.Default.VFD_CommPort, Settings.Default.VFD_CommBaudRate);
            _port.Open();
            //_port.Write(new byte[] { 12, 20, 1 }, 0, 3);
            //_port.Write(new byte[] { 210 }, 0, 1);

            CharMap.Instance.Initialize(_port);

            #region Registo de novo caracter

            //_port.Write(new byte[] { 26 }, 0, 1);
            //_port.Write(new byte[] { 210 }, 0, 1);
            //_port.Write(new byte[] { 30, 1, 1, 14, 0, 0, 0 }, 0, 7);
            //_port.Write(new byte[] { 210 }, 0, 1);

            #endregion

            return true;
        }

        public bool Terminate()
        {
            _port.Close();
            return true;
        }

        public bool WriteLine(int line, string value)
        {
            switch (line)
            {
                case 1:
                    _port.Write(new byte[] { 27, 0 }, 0, 2);
                    break;
                case 2:
                    _port.Write(new byte[] { 27, 20 }, 0, 2);
                    break;
                default:
                    break;
            }

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            _port.Write(CharMap.Instance.GetBytes(value), 0, 20);
            return true;
        }

        #endregion

        #endregion
    }
}
